<template>
  <div class="spec-preview" @mousemove="mouseMove">
    <!-- 设置初始图片显示，避免刷新网页出现图片裂开 -->
    <img v-show='imgUrl' :src="imgUrl" />
    <div class="event"></div>
    <div class="big">
      <img v-show='imgUrl' :src="imgUrl" ref="bigImg" />
    </div>
    <div class="mask" ref="mask"></div>
  </div>
</template>

<script>
export default {
  name: "Zoom",
  props: ["skuDefaultImg"],
  data(){
    return {
      imgUrl:''
    }
  },
  mounted(){
    //初始绑定一个自定义事件，用来接收imageList组件的传递的图片地址
    //  给$bus绑定自定义事件,需要使用箭头函数作为回调函数,因为普通函数的this指向vue实例
    this.$bus.$on('getDetailImageUrl',(imgUrl)=>{
      this.imgUrl = imgUrl;
    })
  },
  methods: {
    // 鼠标在放大镜上的移动事件
    mouseMove(e) {
      let MaskEl = this.$refs.mask;
      let bigImgEL = this.$refs.bigImg;
      // 获取鼠标到容器边缘的距离
      const mouseToBox = {
        x: e.offsetX,
        y: e.offsetY,
      };
      // 获取mask元素的一半宽高
      const maskWH = {
        x: MaskEl.offsetWidth / 2,
        y: MaskEl.offsetHeight / 2,
      };
      // 获取mask需要移动的距离
      const maskMove = {
        x: mouseToBox.x - maskWH.x,
        y: mouseToBox.y - maskWH.y,
      };
      // 边界条件判断
      const distY = e.target.clientHeight - MaskEl.offsetHeight;
      const distX = e.target.clientWidth - MaskEl.offsetWidth;
      if (maskMove.y < 0) {
        maskMove.y = 0;
      } else if (maskMove.y > distY) {
        maskMove.y = distY;
      }
      if (maskMove.x < 0) {
        maskMove.x = 0;
      } else if (maskMove.x > distX) {
        maskMove.x = distX;
      }
      // 赋值
      MaskEl.style.left = maskMove.x + "px";
      MaskEl.style.top = maskMove.y + "px";

      // 控制大图展示
      bigImgEL.style.left = -maskMove.x * 2 + "px";
      bigImgEL.style.top = -maskMove.y * 2 + "px";
    },
  },
  watch:{
    skuDefaultImg(newVal){
      this.imgUrl = newVal;
    }
  }
};
</script>

<style lang="less">
.spec-preview {
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid #ccc;

  img {
    width: 100%;
    height: 100%;
  }

  .event {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 998;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: rgba(0, 255, 0, 0.3);
    position: absolute;
    left: 0;
    top: 0;
    display: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -1px;
    left: 100%;
    border: 1px solid #aaa;
    overflow: hidden;
    z-index: 998;
    display: none;
    background: white;

    img {
      width: 200%;
      max-width: 200%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .event:hover ~ .mask,
  .event:hover ~ .big {
    display: block;
  }
}
</style>